package com.huiyujiaoyu.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.DisplayMetrics;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.huiyujiaoyu.base.AppContext;
import com.huiyujiaoyu.util.DisplayUtil;
import com.orhanobut.logger.Logger;

/**
 * Created by yujunlong on 2016/12/22.
 */

public class SetHeightWebUtil {
    private WebView webview_aboutus;

    public SetHeightWebUtil(WebView webview) {
        webview_aboutus = webview;
        initWebbiew();
    }

    private void initWebbiew() {
        WebSettings webSettings = webview_aboutus.getSettings();
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(true);
        //用来处理一些html的页面内容
        webview_aboutus.setWebViewClient(new webViewClient());
        //丰富的处理效果，比如JS、进度条等
        webview_aboutus.setWebChromeClient(new WebChromeClient());

//        webview_aboutus.getSettings().setDefaultTextEncodingName("UTF -8");
    }

    /**
     * 使用与API17以上
     *
     * @param context
     */
    @SuppressLint("JavascriptInterface")
    public void setDoWhatListener(Context context) {
        // 添加js交互接口类，并起别名 appdowhat
        JavascriptInterface javascriptInterface = new JavascriptInterface(context);
        webview_aboutus.addJavascriptInterface(javascriptInterface, javascriptInterface.toString());
    }

    public void loadUrl(String url) {
        //加载需要显示的网页
        webview_aboutus.loadUrl(url);
        webview_aboutus.reload();
    }

    public void reload() {
        //加载需要显示的网页
        webview_aboutus.reload();
    }

    // 注入js函数监听
    private void infoHtmoJS() {
        // 这段js函数的功能就是，遍历所有的img几点，并添加onclick函数，函数的功能是在图片点击的时候调用本地java接口并传递url过去
        //scrollContent 换成div
        /**
         * 	<div class="m-detail-dynamic">
         * <section class="dynamic-content">
         *  <div class="scrollContent">
         *      document.getElementById('content')
         */
        webview_aboutus.loadUrl("javascript:(function(){" +
                "var _height = document.getElementById(\"content\").offsetHeight;"
                + "window.appdowhat.appDoWhat(_height);"
                + "})()");
    }

    // js通信接口
    public class JavascriptInterface {

        private Context context;

        public JavascriptInterface(Context context) {
            this.context = context;
        }

        @android.webkit.JavascriptInterface
        public void appDoWhat(final int height) {
            AppContext.mHandler.post(new Runnable() {
                @Override
                public void run() {
                    webview_aboutus.setLayoutParams(new LinearLayout.LayoutParams(DisplayUtil.getDensityWdith(context), (int) (height * getDensity(context)+dip2px(webview_aboutus.getContext(),10))));
                    Logger.e("appDoWhat=" + height);
                }
            });
        }

        @android.webkit.JavascriptInterface
        public String toString() {
            return "appdowhat";
        }
    }

    public class WebChromeClient extends android.webkit.WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
//                dismissDialog();
            } else {
//                showWaitDialog();
            }
            super.onProgressChanged(view, newProgress);
        }
    }

    //Web视图
    private class webViewClient extends WebViewClient {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest st) {
            view.loadUrl(st.getUrl().toString());
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {

            view.getSettings().setJavaScriptEnabled(true);

            super.onPageFinished(view, url);
            // html加载完成之后，添加监听图片的点击js函数
            infoHtmoJS();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            view.getSettings().setJavaScriptEnabled(true);
            super.onPageStarted(view, url, favicon);
        }
    }
    public static float getDensity(Context context) {
        Resources resources = context.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        return dm.density;
    }
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

}
